<?php

namespace app\api\controller\admin\setting;

use app\api\common\controller\BaseApi;
use app\api\services\admin\setting\UploadServices;
use app\Request;
use Intervention\Image\ImageManagerStatic as Image;
use think\App;
use think\Exception;
use think\facade\Filesystem;

class UploadController extends BaseApi
{

    private UploadServices $services;

    public function __construct(Request $request, App $app, UploadServices $services)
    {
        parent::__construct($app);
        $this->services = $services;
    }

    /**
     * @throws \ReflectionException
     */
    public function select(Request $request): \think\response\Json
    {
        $where = $request->getParams([
            ['name', '', '', 'name_like'],
            ['category', '', ''],
            ['ext'],
            ['timeKey', 'create_time'],
            ['create_time', '', '', 'time'],
        ]);

        $this->validate($where, [
            'name_like'   => 'max:32',
            'status' => 'in:0,1',
        ], [], true, true);
        $ret = $this->services->select($where);
        return ret_value(0, "ok", $ret['list'], 200, [], ["count" => $ret['count']]);
    }

    /**
     * update
     *
     * @param \app\Request $request
     *
     * @return \think\response\Json
     */
    public function update(Request $request): \think\response\Json
    {

        $id = $request->getParams([
            ['id'],
        ]);

        $data = $request->getParams([
            ['category'],
        ]);
        $this->validate($id, [
            'id' => 'require',
        ], [], true, true);
        $this->validate($data, [
            'category' => 'require',
        ], ['category.require' => '类别不能为空'], true, true);
        $ret = $this->services->update($id, $data);
        if ($ret)
            return ret_value(0, "success");
        else
            return ret_value(0, "Fail");
    }

    /**
     * insert
     *
     * @param \app\Request $request
     *
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function insert(Request $request): \think\response\Json
    {
        // 获取上传的文件
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new Exception('未找到文件');
        }
        try {
            $this->services->uploadFile($file);
            return ret_value(0, "success");
        } catch (\Exception $e) {
            return ret_value(-1, $e->getMessage());
        }
    }

    /**
     * file
     *
     * @param \app\Request $request
     *
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function file(Request $request): \think\response\Json
    {
        // 获取上传的文件
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new Exception('未找到文件');
        }
        try {
            $this->services->uploadFile($file);
            return ret_value(0, "success");
        } catch (\Exception $e) {
            return ret_value(-1, $e->getMessage());
        }
    }

    /**
     * delete
     *
     * @param \app\Request $request
     *
     * @return \think\response\Json
     * @throws \ReflectionException
     */
    public function delete(Request $request): \think\response\Json
    {
        $id = $request->getParams([
            ['id', '', '', 'id_in'],
        ]);
        $this->validate($id, [
            'id_in' => 'require',
        ], [], true, true);

        $ret = $this->services->delete($id);
        if ($ret)
            return ret_value(0, "success");
        else
            return ret_value(0, "Fail");
    }

    /**
     * 头像上传
     *
     * @param \app\Request $request
     *
     * @return \think\response\Json|void
     * @throws \think\Exception
     */
    public function avatar(Request $request, APP $app)
    {
        // 获取上传的文件
        $file = $request->file('file');
        if ($file && $file->isValid()) {
            $ext = strtolower($file->extension());
            if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png'])) {
                throw new Exception('仅支持 jpg jpeg gif png格式');
            }
            $real_path = '/upload/avatar/' . date('Ym');
            $fileName  = Filesystem::disk('local')->putFile($real_path, $file, function () {
                return md5(uniqid());
            });
            $base_path = app()->getRootPath();
            $imageData = file_get_contents($base_path . 'runtime/storage/' . $fileName);
            $base64    = base64_encode($imageData);
            return ret_value(0, "success", ['url' => $fileName, 'img' => "data:image/png;base64,".$base64]);
        }
    }

    /**
     * get
     *
     * @param \app\Request $request
     * @param              $id
     *
     * @return \think\response\Json
     */
    public function get(Request $request, $id): \think\response\Json
    {
        $where = $request->getParams([
            ['id'],
        ]);
        $this->validate($where, [
            'id' => 'require',
        ], [], true, true);
        $ret = $this->services->get($where)->toArray();
        return ret_value(0, 'ok', $ret);
    }
}
